package cn.nawang.ebeim.client.task;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 系统定时任务
 * Created by GanJc on 2016/1/20.
 */
public abstract class TimerTask implements Task,Runnable {

    private static final Logger LOG = LoggerFactory.getLogger(TimerTask.class);

    private ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);

    private boolean start = true ;

    //定时任务的执行周期,子类可重写，改变周期
    protected long getInterval(){
        return 5;
    }

    public void run() {
        while (start){
            try {
                LOG.info("TimerTask start..");
                this.execute();
                LOG.info("TimerTask finish!");
                TimeUnit.SECONDS.sleep(getInterval());
            } catch (Throwable e) {
                LOG.error("TimerTask error:",e);
            }
        }
    }

    public void start(){
        executorService.execute(this);
    }

    public void stop(){
        start = false ;
        executorService.shutdown();
    }

}
